#include "tbcore/base/path.hpp"

#include <boost/filesystem.hpp>

#include "tbcore/base/tostring.hpp"
#include "tbcore/base/logging.hpp"

TB_NAMESPACE_BEGIN

void __WalkDirectory(const _STD string &path, const std::string &ext,
  std::vector<String> &files, int currDepth, int depth) {
  if (depth >= 0 && currDepth > depth) return;

  _STD string path_ = TB_ASCII_STRING(path);

  try {
    boost::filesystem::directory_iterator dirBegin(path_);
    boost::filesystem::directory_iterator dirEnd;

    for (boost::filesystem::directory_iterator it = dirBegin; it != dirEnd; ++it) {
      if (boost::filesystem::is_regular_file((*it).status())) {
        if (ext.empty() || ext == "*" || (*it).path().extension().string() == ext) {
          files.push_back(TB_STRING((*it).path().string()));
        }
      } else if ((depth < 0 || (depth - currDepth) >= 1) &&
        boost::filesystem::is_directory((*it).status())) {
        __WalkDirectory((*it).path().string(), ext, files, currDepth + 1, depth);
      }
    }
  } catch (std::exception &ex) {
    _LERROR() << "exception occured, detail: " << ex.what();
  }
}

void Path::Walk(const String &path, 
  std::vector<String> &files, int depth) {
  _STD string path_ = TB_ASCII_STRING(path);
  __WalkDirectory(path_, "", files, 1, depth);
}

void Path::WalkWithExt(const String &path, const TCHAR *ext, 
  std::vector<String> &files, int depth /*= -1*/) {
  _STD string path_ = TB_ASCII_STRING(path);
  _STD string ext_ = TB_ASCII_STRING(ext);
  __WalkDirectory(path_, ext_, files, 1, depth);
}

String Path::Parent(const String &path) NOEXCEPT {
  return TB_STRING(boost::filesystem::path(TB_ASCII_STRING(path)).parent_path().string());
}

TB_NAMESPACE_END


